#include <iostream>
//#include <fstream>

#include "cv.h"
#include "highgui.h"
#include "motion.h"


using namespace std;

bool motion(IplImage* colourImage,IplImage* movingAverage,IplImage* difference,IplImage* temp){

    int say;

 CvSize imgSize;
 imgSize.width = colourImage->width;
 imgSize.height = colourImage->height;

 IplImage* greyImage = cvCreateImage( imgSize, IPL_DEPTH_8U, 1);
 IplImage* tmp = cvCreateImage( imgSize, IPL_DEPTH_8U, 1);

 
  //Convert the scale of the moving average.
  cvConvertScale(movingAverage,temp, 1.0, 0.0);
 
  //Minus the current frame from the moving average.
  cvAbsDiff(colourImage,temp,difference);
  
  //Convert the image to grayscale.
  cvCvtColor(difference,tmp,CV_RGB2GRAY);
  
  //Convert the image to black and white.
  cvThreshold(tmp, greyImage, 70, 255, CV_THRESH_BINARY);
  
  //Dilate and erode to get people blobs
  cvDilate(greyImage, tmp, 0, 10);
  cvErode(tmp, greyImage, 0, 10);
  say=cvCountNonZero(greyImage);

  //ofstream myfile;
  //myfile.open ("banch.txt", ios::out | ios::app); 
  

  bool is_motion = false;  
  int trash = 38400; //semih

  if (imgSize.width != 640)
      trash = 3200;

  if(trash<=say){
        is_motion = true;
  }

 cvReleaseImage(&greyImage);
 cvReleaseImage(&tmp);
  
 return is_motion;
    }
